﻿using System.Linq.Expressions;
using InvestmentIntelligence.DbModel.Models;
using System;
using System.Collections.Generic;
using System.Linq;

namespace InvestmentIntelligence.Data.Repository.EFImplementation
{
    public class InvestmentRepositoryEF : IIPRepository<Investment>, IInvestmentRepositoryEF
    {
        public List<T> GetSecuritySeriesByBook<T>(Func<IQueryable<InvestmentSecuritySerie>, IEnumerable<T>> f, int fundBookEntityId)
        {
            return GetList(dc => f(from investment in dc
                                     where investment.FundBookEntityId == fundBookEntityId
                                     from series in investment.SecuritySeries
                                     select series));
        }

        public List<Investment> GetList(Expression<Func<Investment, bool>> queryExpression)
        {
            return GetList(dc => dc.Where(queryExpression));
        }

        public Expression<Func<Investment, bool>> GetQueryExpression(int fundBookId)
        {
            var investment = Expression.Parameter(typeof(Investment), "inv");

            var fundBookIdExp = Expression.Property(investment, "FundBookEntityId");
            var inputIdExp = Expression.Constant(fundBookId);
            var equalIdExp = Expression.Equal(fundBookIdExp, inputIdExp);

            var queryExpression = Expression.Lambda<Func<Investment, bool>>(equalIdExp, investment);
            return queryExpression;
        }

        public List<InvestmentSecuritySerie> GetSecuritySeries(Expression<Func<Investment, bool>> queryExpression, List<int> securityIds)
        {
            return GetList(dc => dc
                .Where(queryExpression)
                .SelectMany(k => k.SecuritySeries)
                .Where(ss => securityIds.Contains(ss.SecurityId)));
        }
    }
}
